#include "../DWMRICore/Fiber.h"
#include "../DWMRICore/DTI.h"
#include "../DWMRICore/Scalar.h"

#include <teem/ten.h>

#include <omp.h>

#define _USE_MATH_DEFINES
#include <math.h>
#include <time.h>

#include <string>

using namespace std;

char *pDTIPathname = NULL;				/* input diffusion tensor pathname */
char *pWMMASKPathname = NULL;			/* input white matter mask pathname */
char *pBrainMASKPathname = NULL;		/* inout brain mask pathname */
char *pFiberPathname = NULL;			/* output fiber configure pathname */

float stepSize = 0.1f;
float maxLength = 50.0f;
float faThreshold = 0.06f;
float angleThreshold = 0.707f;
int scale = 1;
int innerSteps = 10;


/* MLS fiber tracking parameters */
float MLSSize = 1.0f;
CPoint3F *pSamplePoints = NULL;
float *pSamplePointsWeight = NULL;

CDTI *pDTI = NULL;					/* DTI */
CScalar *pWMMASK = NULL;			/* white matter mask */
CScalar *pBrainMASK = NULL;			/* brain mask */

const float MASK_THRESHOLD = 0.06f;

void PrintUsage()
{
	printf("Usage: ");
	printf("DTIFiberTracking -dti <DTI> -wm_mask <White Matter MASK> -brain_mask <Brain MASK> -fiber <Fiber> [-stepsize <stepsize> -maxlength <maxlength> -fa_thresold <fa_threshold> -angle_threshold <fa_threshold> -scale <scale>]\n");
	printf("\n");
	//printf("-vec <VectorField> = input VectorField nrrd file\n");
	//printf("-fiber <Fiber> = output Fiber configure file\n");
	//printf("-stepsize <stepsize> = step size\n");
	//printf("-maxlength <maxlength> = maximum fiber length\n");
	//printf("-fa_threshold <fa_thresold> = FA threshold used to differ white matter and grey matter\n");
	//printf("-angle_threshold <angle_thresold> = angle threshold between two directions, in cosine\n");
	//printf("-scale <scale> = scale of the result\n");
}


int ParseArguments(const int argc, char *argv[])
{
	for (int i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "-dti") == 0) {
			pDTIPathname = argv[++i];
		} else if (strcmp(argv[i], "-wm_mask") == 0) {
			pWMMASKPathname = argv[++i];
		} else if (strcmp(argv[i], "-brain_mask") == 0) {
			pBrainMASKPathname = argv[++i];
		} else if (strcmp(argv[i], "-fiber") == 0) {
			pFiberPathname = argv[++i];
		} else if (strcmp(argv[i], "-stepsize") == 0) {
			stepSize = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-maxlength") == 0) {
			maxLength = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-fa_threshold") == 0) {
			faThreshold = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-angle_threshold") == 0) {
			angleThreshold = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-scale") == 0) {
			scale = (float)atof(argv[++i]);
		} else {
            printf("unknown %s\n", argv[i]);
			return 1;		// error
		}
	}

	if (pDTIPathname == NULL || pBrainMASKPathname == NULL || pWMMASKPathname == NULL || pFiberPathname == NULL)
		return -2;

	return 0;
}


void CreateMLSSamplePoints()
{
	SafeDeleteArray(pSamplePoints);
	SafeDeleteArray(pSamplePointsWeight);
	pSamplePoints = new CPoint3F[SAMPLE_POINT_NUM];
	pSamplePointsWeight = new float[SAMPLE_POINT_NUM];

	pSamplePoints[0].m_x = 0.0f;
	pSamplePoints[0].m_y = 0.0f;
	pSamplePoints[0].m_z = 0.0f;
	pSamplePointsWeight[0] = 1.0f;

	clock_t seed = clock();
	srand(seed);

	for (int i = 1; i < SAMPLE_POINT_NUM; ++i) {
		bool flag = false;
		CPoint3F pt;
		while(!flag) {
			float a = (float)rand() / (float)RAND_MAX * 2.0f * (float)M_PI;
			float b = (float)rand() / (float)RAND_MAX * (float)M_PI;
			float r = (float)rand() / (float)RAND_MAX;

			pt.m_x = r * sinf(a) * sinf(b);
			pt.m_y = r * sinf(a) * cosf(b);
			pt.m_z = r * cosf(a);

			flag = true;
			for (int j = 0; j < i; ++j) {
				float dis = Distance(pSamplePoints[j], pt);
				if (dis < 0.3f) {
					flag = false;
					break;
				}
			}
		}

		pSamplePoints[i] = pt;
		pSamplePointsWeight[i] = InnerProduct(pSamplePoints[i], pSamplePoints[i]) * 4.0f;
		pSamplePointsWeight[i] = expf(pSamplePointsWeight[i] / -2.5f);
	}
}

//void DTIMLSFilter(const CPoint3F pos, float *lastDTI, float *filteredDTI)
//{
//	pDTI->GetDTI(pos, filteredDTI);
//}

void DTIMLSFilter(const CPoint3F pos, float *lastDTI, float *filteredDTI)
{
	float m[9];
	TEN_T2M(m, lastDTI);

	CPoint3F samples[SAMPLE_POINT_NUM];
	float length[SAMPLE_POINT_NUM];
	float max_length = 0.0f;
	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		samples[i].m_x = pSamplePoints[i].m_x * m[0] + pSamplePoints[i].m_y * m[1] + pSamplePoints[i].m_z * m[2];
		samples[i].m_y = pSamplePoints[i].m_x * m[3] + pSamplePoints[i].m_y * m[4] + pSamplePoints[i].m_z * m[5];
		samples[i].m_z = pSamplePoints[i].m_x * m[6] + pSamplePoints[i].m_y * m[7] + pSamplePoints[i].m_z * m[8];
		length[i] = sqrtf(InnerProduct(samples[i], samples[i]));
		if (length[i] > max_length)
			max_length = length[i];
	}

	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		samples[i].m_x = samples[i].m_x / max_length * MLSSize + pos.m_x;
		samples[i].m_y = samples[i].m_y / max_length * MLSSize + pos.m_y;
		samples[i].m_z = samples[i].m_z / max_length * MLSSize + pos.m_z;
	}

	memset(filteredDTI, 0, sizeof(float)*7);
	float temp_DTI[7];
	float weight = 0.0f;
	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		if (pBrainMASK->GetScalar(samples[i]) < MASK_THRESHOLD) {
			continue;
		}
		//if (pWMMASK->GetScalar(samples[i]) > 0.4f || pWMMASK->GetScalar(samples[i]) < 0.2f) {
		//	continue;
		//}
		pDTI->GetDTI(samples[i], temp_DTI);

		for (uint j = 0; j < 7; ++j) {
			filteredDTI[j] += pSamplePointsWeight[i] * temp_DTI[j];
		}
		weight += pSamplePointsWeight[i];
	}

	for (uint j = 0; j < 7; ++j) {
		filteredDTI[j] = filteredDTI[j] / weight;
	}
}

int GetNextDirection(const CPoint3F pos, CVector3F *in, float *lastDTI, CVector3F *out)
{
	//if (pBrainMASK->GetScalar(pos) < 0.5f || pWMMASK->GetScalar(pos) > 0.4f || pWMMASK->GetScalar(pos) < 0.2f) {
	//	return 0;
	//}
	if (pBrainMASK->GetScalar(pos) < MASK_THRESHOLD) {
		return 0;
	}

	float filteredDTI[7];
	DTIMLSFilter(pos, lastDTI, filteredDTI);
	//pDTI->GetDTI(pos, filteredDTI);
	memcpy(lastDTI, filteredDTI, sizeof(float)*7);

	float fa = pDTI->DTI2FA(filteredDTI);
	if (fa < faThreshold)
		return 0;

	CVector3F dir;
	pDTI->DTI2Direction(filteredDTI, &dir);


	float v = InnerProduct(in, &(dir));

	if (fabs(v) > angleThreshold) {
		if (v < 0.0f) {
			out->m_x = -dir.m_x;
			out->m_y = -dir.m_y;
			out->m_z = -dir.m_z;
		} else {
			out->m_x = dir.m_x;
			out->m_y = dir.m_y;
			out->m_z = dir.m_z;
		}
		return 1;
	} else {
		return 0;
	}
}

int ComputeNextPositionRK2(CPoint3F lastPos, CVector3F lastDir, 
	float *lastDTI,	CPoint3F &nextPos, CVector3F &nextDir)
{
	CVector3F k1 = lastDir * stepSize;
	CPoint3F p = lastPos + k1 / 2.0f;
	CVector3F v;
	if (GetNextDirection(p, &lastDir, lastDTI, &v) == 0) {
		return 0;
	}

	CVector3F k2 = v * stepSize;

	nextPos = lastPos + k2;

	if (GetNextDirection(nextPos, &lastDir, lastDTI, &nextDir) == 0) {
		return 0;
	}

	return 1;
}

int TrackingFibers(CFiber **fibers, CPoint3F pos)
{
	float initDTI[7] = {1, 1, 0, 0, 1, 0, 1};
	float filteredDTI[7];
	DTIMLSFilter(pos, initDTI, filteredDTI);
	//pDTI->GetDTI(pos, filteredDTI);
	float fa = pDTI->DTI2FA(filteredDTI);

	CVector3F dir;
	//if (pos.m_z < 55.0f || pos.m_z > 79.9f || pos.m_x < 30.0f || pos.m_x > 59.9f) {
	//	// not in the interesting region
	//	dir = CVector3F(0.0f, 0.0f, 0.0f);
	//} else {
		if (fa < faThreshold /*|| pBrainMASK->GetScalar(pos) < 0.5f*/) {
			dir = CVector3F(0, 0, 0);
		} else {
			pDTI->DTI2Direction(filteredDTI, &dir);
		}
	//}
		
	//if (pBrainMASK->GetScalar(pos) < 0.5f || pWMMASK->GetScalar(pos) > 0.4f || pWMMASK->GetScalar(pos) < 0.2f) {
	//	dir = CVector3F(0, 0, 0);
	//} else {
	//	pDTI->DTI2Direction(filteredDTI, &dir);
	//}
	
	

	int count = 1;
	*fibers = new CFiber[count];
	
	for (int i = 0; i < count; ++i) {
		Seed seed;
		seed.pos = pos;
		seed.dir = dir;

		uint maxSteps = (uint)(maxLength / (stepSize * (float)innerSteps));
		uint fnum, bnum;
		CPoint3F *pF = new CPoint3F[maxSteps];
		CPoint3F *pB = new CPoint3F[maxSteps];
		CPoint3F lastPos;
		CVector3F lastDir;
		float lastDTI[7];

		/* tracking forward */
		memcpy(lastDTI, filteredDTI, sizeof(float)*7);
		lastPos = seed.pos;
		lastDir = seed.dir;
		pF[0] = lastPos;
		for (fnum = 1; fnum < maxSteps; ++fnum) {
			CPoint3F nextPos;
			CVector3F nextDir;

			bool flag = true;
			for (int step = 0; step < innerSteps; ++step) {
				if (ComputeNextPositionRK2(lastPos, lastDir, lastDTI, nextPos, nextDir) == 0) {
					flag = false;
					break;
				}
				lastDir = nextDir;
				lastPos = nextPos;
			}
			if (flag == false)
				break;

			pF[fnum] = nextPos;
			lastDir = nextDir;
			lastPos = nextPos;
		}

		/* tracking backward */
		memcpy(lastDTI, filteredDTI, sizeof(float)*7);
		lastPos = seed.pos;
		lastDir.m_x = -seed.dir.m_x;
		lastDir.m_y = -seed.dir.m_y;
		lastDir.m_z = -seed.dir.m_z;
		pB[0] = lastPos;
		for (bnum = 1; bnum < maxSteps; ++bnum) {
			CPoint3F nextPos;
			CVector3F nextDir;

			bool flag = true;
			for (int step = 0; step < innerSteps; ++step) {
				if (ComputeNextPositionRK2(lastPos, lastDir, lastDTI, nextPos, nextDir) == 0) {
					flag = false;
					break;
				}
				lastDir = nextDir;
				lastPos = nextPos;
			}
			if (flag == false)
				break;

			pB[bnum] = nextPos;
			lastDir = nextDir;
			lastPos = nextPos;
		}

		(*fibers)[i].CreateFiber(pF, pB, fnum, bnum, &seed);

		SafeDeleteArray(pF);
		SafeDeleteArray(pB);
	}

	return count;
}

void DTIFiberTracking()
{
	uint w = pDTI->GetWidth();
	uint h = pDTI->GetHeight();
	uint d = pDTI->GetDepth();

	int sw = (int)w * scale;
	int sh = (int)h * scale;
	int sd = (int)d * scale;

	FILE *fp = fopen(pFiberPathname, "w");
	fprintf(fp, "%d %d %d %d %f %f\n", sw, sh, sd, (int)scale, stepSize, maxLength);

	std::string pathname = pFiberPathname;
	size_t pos = pathname.find_last_of(SLASH);
	std::string path = pathname.substr(0, pos+1);
	
	omp_set_num_threads(16);

	for (int z = 49; z < 50; ++z) {
		printf("Fiber tracking on slice z = %d ... ", z);

		CFiber **fibers = new CFiber*[sw*sh];
		memset(fibers, NULL, sizeof(CFiber*)*sw*sh);
		int *count = new int[sw*sh];
		memset(count, 0, sizeof(int)*sw*sh);

		for (int y = 124; y < 138; ++y) {
#pragma omp parallel for schedule(dynamic, 1)
			for (int x = 82; x < 101; ++x) {
				CPoint3F pos = CPoint3F();
				pos.m_x = (float)x/(float)scale;
				pos.m_y = (float)y/(float)scale;
				pos.m_z = (float)z/(float)scale;
				int index = y * sw + x;
				count[index] = TrackingFibers(&(fibers[index]), pos);
			}
			float ff = float(y+1) / float(sh) * 100.0f;
			printf("\rFiber tracking on slice z = %d ... %.3f%%", z, ff);
		}

		char confPathname[PATHNAME_SIZE];
		char vertPathname[PATHNAME_SIZE];
		sprintf(confPathname, "%sslice_z=%08.04f.conf", path.c_str(), (float)z/(float)scale);
		sprintf(vertPathname, "%sslice_z=%08.04f.vert", path.c_str(), (float)z/(float)scale);
		fprintf(fp, "%s\t%s\n", confPathname, vertPathname);

		SaveFibers(confPathname, vertPathname, fibers, count, sw, sh);
		//SaveFibersAsVTK("C:\\Ziang\\Dataset\\Alex\\2X\\ForFiberTracking\\test.vtk", fibers, count, sw, sh);

		for (int i = 0; i < sw*sh; ++i) {
			SafeDeleteArray(fibers[i]);
		}
		SafeDeleteArray(fibers);
		SafeDeleteArray(count);

		printf("\rFiber tracking on slice z = %d ... 100.0%% Done.\n", z);
	}


//	for (int x = sw/2; x < sw/2+1; ++x) {
//		printf("Fiber tracking on slice x = %d ... ", x);
//
//		CFiber **fibers = new CFiber*[sh*sd];
//		memset(fibers, NULL, sizeof(CFiber*)*sh*sd);
//		int *count = new int[sh*sd];
//		memset(count, 0, sizeof(int)*sh*sd);
//
//		for (int z = 0; z < sd; ++z) {	
//#pragma omp parallel for schedule(dynamic, 1)
//			for (int y = 0; y < sh; ++y) {
//				CPoint3F pos = CPoint3F();
//				pos.m_x = (float)x/(float)scale;
//				pos.m_y = (float)y/(float)scale;
//				pos.m_z = (float)z/(float)scale;
//				int index = z * sh + y;
//				count[index] = TrackingFibers(&(fibers[index]), pos);
//			}
//			float ff = float(z+1) / float(sd) * 100.0f;
//			printf("\rFiber tracking on slice x = %d ... %.3f%%", x, ff);
//		}
//
//		char confPathname[PATHNAME_SIZE];
//		char vertPathname[PATHNAME_SIZE];
//		sprintf(confPathname, "%sslice_x=%08.04f.conf", path.c_str(), (float)x/(float)scale);
//		sprintf(vertPathname, "%sslice_x=%08.04f.vert", path.c_str(), (float)x/(float)scale);
//		fprintf(fp, "%s\t%s\n", confPathname, vertPathname);
//
//		//SaveFibers(confPathname, vertPathname, fibers, count, sh, sd);
//		SaveFibersAsVTK("C:\\Ziang\\Dataset\\Alex\\2X\\ForFiberTracking\\test.vtk", fibers, count, sh, sd);
//
//		for (int i = 0; i < sh*sd; ++i) {
//			SafeDeleteArray(fibers[i]);
//		}
//		SafeDeleteArray(fibers);
//		SafeDeleteArray(count);
//
//		printf("\rFiber tracking on slice x = %d ... 100.0%% Done.\n", x);
//	}

	fclose(fp);
}

int main(int argc, char *argv[])
{
	if (ParseArguments(argc, argv) != 0) {
		PrintUsage();
		return 0;
	}

	pDTI = new CDTI();
	pDTI->OpenDTIFile(pDTIPathname);
	pWMMASK = new CScalar();
	pWMMASK->OpenScalarFile(pWMMASKPathname);
	pBrainMASK = new CScalar();
	pBrainMASK->OpenScalarFile(pBrainMASKPathname);

	CreateMLSSamplePoints();

	DTIFiberTracking();

	SafeDelete(pDTI);
	SafeDelete(pWMMASK);

	return 0;
}
